from flask import Flask, request, jsonify, send_from_directory, make_response, render_template
from flask_cors import CORS
from gensim.models.word2vec import Word2Vec
import os
import logging

'''
1.日志设置
'''
# 配置日志 设置日志级别为 INFO
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)  # __name__ = app
print(logger)

# 设置gensim的日志级别为warning 不会干扰别的日志
logger_gensim = logging.getLogger('gensim').setLevel(logging.WARNING)


# 创建一个过滤器，排除特定路径的日志
class DevToolsFilter(logging.Filter):
    def filter(self, record):
        return '/.well-known/appspecific/com.chrome.devtools.json' not in record.getMessage()


# 应用过滤器到Werkzeug的日志记录器
logging.getLogger('werkzeug').addFilter(DevToolsFilter())

'''
2.设置模型路径并加载模型
'''
# 加载 Word2Vec 模型   os.path.dirname(__file__) 当前文件的工作目录
MODEL_PATH = os.path.join(os.path.dirname(__file__), 'model', 'm_wv_model2.model')
try:
    model = Word2Vec.load(MODEL_PATH)
    logger.info("Word2Vec 模型加载成功")
except Exception as e:
    logger.error(f'模型加载失败：{e}')
    raise  # 把异常重新抛出给上层，让调用代码的函数或模块来处理

'''
3.创建app
'''
test_config = None
app = Flask(__name__, instance_relative_config=True)
# 设置应用程序将使用的一些默认配置
app.config.from_mapping(
    SECRET_KEY='dev',
    DATABASE=os.path.join(app.instance_path, 'app.sqlite'),
)
CORS(app)

if test_config is None:
    # load the instance config, if it exists, when not testing
    app.config.from_pyfile('config.py', silent=True)
else:
    # load the test config if passed in
    app.config.from_mapping(test_config)

    # ensure the instance folder exists
try:
    os.makedirs(app.instance_path)
except OSError:
    pass

    # 拿db.py中的函数
    import db
    db.init_app(app)

    # 拿auth中的蓝图
    import auth
    app.register_blueprint(auth.bp)
'''
4.API 路由实现
'''


# 注册接口

# 登录接口

# 网站主页
@app.route('/home')
def home():
    home = make_response(send_from_directory(
        os.path.join(os.path.dirname(__file__), 'templates'),
        'home5.html'
    ))
    return home


@app.route('/custom_response')
def custom_response():
    response = make_response(send_from_directory(
        os.path.join(os.path.dirname(__file__), 'templates'),
        'index.html'
    ))
    # 自定义Response Headers X-Custom-Header: Value
    response.headers['X-Custom-Header'] = 'Value'
    return response


@app.route('/check_word', methods=['GET', 'POST'])
def check_word():
    """
    检查词汇是否存在于 Word2Vec 模型中
    GET 请求示例: /check_word?word=ᠶᠢᠨ
    POST 请求示例: {"word": "ᠶᠢᠨ"}
    """
    try:
        # 获取输入的词汇
        if request.method == 'GET':
            # .get(key, default) key存在返回key对应值，不存在返回default
            # .strip() 去掉字符串空格、换行符、制表符等
            word = request.args.get('word', '').strip()
        else:
            data = request.get_json()
            word = data.get('word', '').strip()

        if not word:
            return jsonify({"error": "请输入要查询的词汇"}), 400

        # 检查词汇是否在模型中
        if word in model.wv:
            vector = model.wv[word].tolist()  # 将 numpy 数组转换为 list
            response = {
                "word": word,
                "in_vocabulary": True,
                "vector": vector,
                "vector_dim": len(vector)
            }
            logger.info(f"找到词汇: {word}")
            # logger.info(f"向量: {vector}")
        else:
            response = {
                "word": word,
                "in_vocabulary": False,
                "message": f"词汇 '{word}' 不在模型中"
            }
            logger.info(f"未找到词汇: {word}")

        return jsonify(response)

    except Exception as e:
        logger.error(f"处理请求时出错: {e}")
        return jsonify({"error": str(e)}), 500


@app.route('/api/get_vector', methods=['GET'])
def get_vector():
    word = request.args.get('word')
    model_name = request.args.get('model')

    if not word:
        return jsonify({'error': '缺少word参数'}), 400

    try:
        if word in model.wv:
            vector = model.wv[word].tolist()
            return jsonify({
                'vector': vector,
                'dimension': len(vector),
                'word': word,
                'model': model_name
            })
        else:
            return jsonify({'error': f'单词"{word}"不在词汇表中'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    print("\n * 请访问: http://127.0.0.1:5000/custom_response")
    print(" * 按 Ctrl+C 退出\n")
    app.run(debug=True)

'''
运行命令
    flask --app app run 
    flask --app app init-db
'''
